import React, { PureComponent } from 'react';
import { connect, routerRedux } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { AdvancedSearch, codeType, DATA_ENTRY, PrimaryC, PrimaryGhostC, RangeDateC, TableC, UploadC } from '../../../../comps';
import styles from './index.less';
import { exportFile } from '../../../../utils/commonFunc';
import moment from 'moment';
import { fixedNum } from '../../../../utils/utils';
import config from '@/src/comps/business/tradingMarket/config';

@Form.create()
@connect(({ loading, workStationM }) => ({ loading, workStationM }))
export default class TransactionManage extends PureComponent {
  state = {
    realParams: {
      startDate: '',
      endDate: '',
      // 证券代码
      tradingCode: undefined,
      // 交易市场
      exchangeCode: undefined,
      // 组合id
      cpCode: '',
    },
    realDataSource: [],
    realColumn: [],

    columns: [
      {
        // 	表格头
        key: 'tradingcode',
        title: '证券代码',
      },
      {
        key: 'chiname',
        title: '证券名称',
      },
      {
        key: 'tradeTime',
        title: '交易时间',
        type: 'date',
      },
      {
        key: 'tradeType',
        title: '交易方向',
      },
      {
        key: 'amount',
        title: '交易数量',
        type: 'number',
      },
      {
        key: 'price',
        title: '交易价格',
        type: 'money',
      },
      {
        key: 'volume',
        title: '交易金额',
        type: 'money',
      },
      {
        key: 'poundage',
        title: '交易费用',
        type: 'money',
      },
    ],
    dataSource: [], // 表格数据
    query: {
      // 查询条件
      startDate: moment().format('YYYY-MM-DD'),
      endDate: moment().format('YYYY-MM-DD'),
    },
    currentPage: 1, // 页码
    pageSize: 10, // 每页数量
  };

  getRealData = () => {
    //真实产品portfolioId组合
    const realPortfolioTypeArray = [];
    if (this.state.isProductCodeUndefined === undefined) {
      for (const item of this.props.workStationM.portfolioList) {
        if (item.portfolioType == 1) {
          realPortfolioTypeArray.push(item.portfolioId);
        }
      }
      this.setState({
        realPortfolioTypeArray,
      });
    }

    this.props.dispatch({
      type: 'tansactionRecordquiryM/queryFnd',
      payload: {
        ...this.state.realParams,
        page: this.state.currentPage,
        pageSize: this.state.pageSize,
        cpCode: this.state.isProductCodeUndefined === undefined ? realPortfolioTypeArray : [this.state.realParams.cpCode],
        isHkStk: '0',
        type: '10',
        timestamp: new Date().getTime(),
      },
      callback: (res) => {
        if (res.data) {
          this.setState({
            realDataSource: res.data,
            total: res.total,
          });
        } else {
          this.setState({
            realDataSource: [],
          });
        }
      },
    });
  };
  // 获取表头
  getColumn = () => {
    this.props.dispatch({
      type: 'workStationM/queryShowCol',
      payload: { type: 'STK_FLOW', isHkStk: 0 },
      callback: (data) => {
        const copyColumn = _.cloneDeep(data);
        copyColumn.map((v) => {
          if (v.dataIndex === 'fundName') {
            v.width = 130;
          }
          if (v.dataIndex === 'portfolioInfoName') {
            v.width = 130;
          }
          if (v.dataIndex === 'jysc') {
            v.width = 130;
          }
          if (v.dataIndex === 'tradeBalance' || v.dataIndex === 'tradePrice') {
            v.type = 'money';
          }
          if (v.dataIndex === 'tradeAmount') {
            v.render = (text) => fixedNum(text, 0);
          }
          if (v.key == 'dataDt' || v.key == 'confirmDt') {
            v.render = (text) => {
              if (text != '--' && text) {
                return text.slice(0, 4) + '-' + text.slice(4, 6) + '-' + text.slice(6);
              } else {
                return '--';
              }
            };
          }
          if (v.key == 'jysc') {
            v.render = (text, record) => {
              if (record?.exchangecode) {
                let findvalue = config.filter((item) => {
                  return item.value == record.exchangecode;
                });
                if (findvalue && findvalue.length > 0) {
                  return findvalue[0].title;
                } else {
                  return '--';
                }
              } else {
                return '--';
              }
            };
          }
        });
        // this.setState({
        //   realColumn: copyColumn,
        // })
        this.setState({
          realColumn: [
            {
              // 	表格头
              key: 'tradingcode',
              title: '证券代码',
              render: (text, record) => {
                if (record?.exchangecode) {
                  let findvalue = config.filter((item) => {
                    return item.value == record.exchangecode;
                  });
                  if (findvalue && findvalue.length > 0) {
                    return text ? text + '.' + findvalue[0].abbr : '--';
                  } else {
                    return '--';
                  }
                } else {
                  return '--';
                }
              },
            },
            {
              key: 'zqName',
              title: '证券简称',
            },
            {
              key: 'dataDt',
              title: '交易时间',
              type: 'date',
            },
            {
              key: 'jyfx',
              title: '交易方向',
            },
            {
              key: 'tradeAmount',
              title: '交易数量',
              type: 'number',
            },
            {
              key: 'tradePrice',
              title: '交易价格',
              type: 'money',
            },
            {
              key: 'tradeBalance',
              title: '交易金额',
              type: 'money',
            },
            {
              key: 'fee',
              title: '交易费用',
              type: 'money',
            },
          ],
        });
      },
    });
  };

  updateQuery = (currentProps) => {
    let endDate = moment().format('YYYYMMDD') - moment(this.props.maxDate).format('YYYYMMDD') > 0 ? moment(this.props.maxDate) : moment();
    let startDate = +moment(endDate).subtract(1, 'months').format('YYYYMMDD') - moment(this.props.minDate).format('YYYYMMDD') > 0 ? moment(endDate).subtract(1, 'months') : moment(this.props.minDate);
    if (this.props.workStationM?.CombinationType?.portfolioType === '1') {
      this.getColumn();
      const startDate = this.state.date.props.form.getFieldsValue().startDate
        ? moment(this.state.date.props.form.getFieldsValue().startDate).format('YYYY-MM-DD')
        : moment().format('YYYY-MM-DD');
      const endDate = this.state.date.props.form.getFieldsValue().endDate
        ? moment(this.state.date.props.form.getFieldsValue().endDate).format('YYYY-MM-DD')
        : moment().format('YYYY-MM-DD');
      this.setState(
        {
          realParams: {
            ...this.state.realParams,
            startDate,
            endDate,
            // 组合id
            cpCode: currentProps.productCode === undefined ? undefined : currentProps.workStationM?.CombinationType?.portfolioId,
          },
          isProductCodeUndefined: currentProps.productCode,
        },
        () => {
          this.getRealData();
        },
      );
    } else {
      this.setState(
        {
          query: {
            portfolioId: currentProps.productCode,
            startDate: startDate.format('YYYY-MM-DD'),
            endDate: endDate.format('YYYY-MM-DD'),
          },
        },
        () => this.getData(),
      );
    }
  }
  componentDidMount() {
    this.updateQuery(this.props);
  }
  UNSAFE_componentWillReceiveProps(nextProps) {
    const init = !this.props.productCode ? '' : JSON.stringify(this.props.productCode);
    const initN = !nextProps.productCode ? '' : JSON.stringify(nextProps.productCode);
    const {
      form: { setFieldsValue },
      minDate,
      maxDate,
    } = this.props;

    const thisPortfolioId = this.props.workStationM?.CombinationType.portfolioId;
    const nextPortfolioId = nextProps.workStationM?.CombinationType.portfolioId;

    let endDate = moment().format('YYYYMMDD') - moment(maxDate).format('YYYYMMDD') > 0 ? moment(maxDate) : moment();
    let startDate = +moment(endDate).subtract(1, 'months').format('YYYYMMDD') - moment(minDate).format('YYYYMMDD') > 0 ? moment(endDate).subtract(1, 'months') : moment(minDate);
    if (init != initN && thisPortfolioId == nextPortfolioId) {
      setTimeout(() => {
        this.RangeDateRef?.setDate([startDate, endDate]);
      }, 500);

      // 真实
      this.updateQuery(nextProps);
      // if (this.props.workStationM?.CombinationType?.portfolioType === '1') {
      //   this.getColumn();
      //   const startDate = this.state.date.props.form.getFieldsValue().startDate
      //     ? moment(this.state.date.props.form.getFieldsValue().startDate).format('YYYY-MM-DD')
      //     : moment().format('YYYY-MM-DD');
      //   const endDate = this.state.date.props.form.getFieldsValue().endDate
      //     ? moment(this.state.date.props.form.getFieldsValue().endDate).format('YYYY-MM-DD')
      //     : moment().format('YYYY-MM-DD');
      //   this.setState(
      //     {
      //       realParams: {
      //         ...this.state.realParams,
      //         startDate,
      //         endDate,
      //         // 组合id
      //         cpCode: nextProps.productCode === undefined ? undefined : nextProps.workStationM?.CombinationType?.portfolioId,
      //       },
      //       isProductCodeUndefined: nextProps.productCode,
      //     },
      //     () => {
      //       this.getRealData();
      //     },
      //   );
      // } else {
      //   this.setState(
      //     {
      //       query: {
      //         portfolioId: nextProps.productCode,
      //         startDate: startDate.format('YYYY-MM-DD'),
      //         endDate: endDate.format('YYYY-MM-DD'),
      //       },
      //     },
      //     () => this.getData(),
      //   );
      // }
    }

    if (thisPortfolioId != nextPortfolioId && init == initN) {
      setTimeout(() => {
        this.RangeDateRef?.setDate([startDate, endDate]);
      }, 500);

      // 真实
      if (nextProps.workStationM?.CombinationType?.portfolioType === '1') {
        this.getColumn();
        const startDate = this.state.date?.props.form.getFieldsValue().startDate
          ? moment(this.state.date?.props.form.getFieldsValue().startDate).format('YYYY-MM-DD')
          : moment().format('YYYY-MM-DD');
        const endDate = this.state.date?.props.form.getFieldsValue().endDate
          ? moment(this.state.date?.props.form.getFieldsValue().endDate).format('YYYY-MM-DD')
          : moment().format('YYYY-MM-DD');
        this.setState(
          {
            realParams: {
              ...this.state.realParams,
              startDate,
              endDate,
              // 组合id
              cpCode: nextProps.productCode === undefined ? undefined : nextProps.workStationM?.CombinationType?.portfolioId,
            },
            isProductCodeUndefined: nextProps.productCode,
          },
          () => {
            this.getRealData();
          },
        );
      } else {
        this.setState(
          {
            query: {
              portfolioId: nextProps.productCode,
              startDate: startDate.format('YYYY-MM-DD'),
              endDate: endDate.format('YYYY-MM-DD'),
            },
          },
          () => this.getData(),
        );
      }
    }
    if (this.props.updateState != nextProps.updateState) {
      if (this.state.query.portfolioId) {
        this.getData();
      }
    }
  }
  // 获取交易管理列表
  getData = () => {
    this.props.dispatch({
      type: 'workStationM/queryTransactionData',
      payload: {
        ...this.state.query,
        Page: this.state.currentPage,
        Size: this.state.pageSize,
      },
      callback: (res) => {
        if (res) {
          this.setState({
            dataSource: res.dataSource,
          });
        } else if ([null, undefined].includes(res)) {
          this.setState({
            dataSource: [],
          });
        }
      },
    });
  };

  // 日期变化响应
  dateChange = (e) => {
    this.setState(
      {
        query: {
          ...this.state.query,
          startDate: moment(e[0]).format('YYYY-MM-DD'),
          endDate: moment(e[1]).format('YYYY-MM-DD'),
        },
      },
      () => this.getData(),
    );
  };

  // 表格页码响应
  handleTableChange = (pagination) => {
    const { current, pageSize } = pagination;
    if (this.props.workStationM?.CombinationType?.portfolioType === '1') {
      this.setState(
        {
          ...this.state.realParams,
          currentPage: current,
          pageSize: pageSize,
        },
        () => this.getRealData(),
      );
    } else {
      this.setState(
        {
          ...this.state.query,
          currentPage: current,
          pageSize: pageSize,
        },
        () => this.getData(),
      );
    }
  };

  // 导出交易
  export = () => {
    exportFile('gateway/maat-workstation/barraTransaction/export', this.state.query);
  };

  // 模板下载
  download = () => {
    exportFile('gateway/maat-workstation/barraTransaction/download');
  };

  // 导入交易
  importTransaction = (file) => {
    const formData = new FormData();
    formData.append('file', file);
    this.props.dispatch({
      type: 'workStationM/importTransaction',
      payload: { formData, portfolioId: this.state.query.portfolioId },
      callback: (data) => {
        if (data) {
          this.props.changeEdit();
          this.props.changeUpdataState();
        }
      },
    });
  };
  // 操作栏按钮
  searchDocker = (e) => {
    if (e) {
      const { startDate, endDate, exchangeCode, tradingCode } = e;
      this.setState(
        {
          realParams: {
            ...this.state.realParams,
            startDate: moment(startDate).format('YYYY-MM-DD'),
            endDate: moment(endDate).format('YYYY-MM-DD'),
            // 证券代码
            tradingCode,
            // 交易市场
            exchangeCode,
          },
        },
        () => this.getRealData(),
      );
    } else {
      const copy = JSON.parse(JSON.stringify(this.state.realParams));
      this.setState(
        {
          realParams: {
            ...this.state.realParams,
            startDate: moment().format('YYYY-MM-DD'),
            endDate: moment().format('YYYY-MM-DD'),
            tradingCode: undefined,
            exchangeCode: undefined,
          },
        },
        () => {
          const { startDate, endDate, tradingCode, exchangeCode } = this.state.realParams;
          console.log(this.state.realParams, copy);
          if (copy.startDate !== startDate || copy.endDate !== endDate || copy.exchangeCode !== exchangeCode || copy.tradingCode !== tradingCode) {
            this.getRealData();
          }
        },
      );
    }
  };
  moreJournal = () => {
    const { startDate, endDate, exchangeCode, tradingCode, cpCode } = this.state.realParams;
    const JYLS_pageJump = {
      //原页面已有带参数 跳转处理，这里保持一致 避免写多个存储处理; 在流水查询中 判断有无cpcode 对他进行表单赋值
      HkStkType: '1', //0-普通股票  1-港股
      tabKey: 'Stock',
      startDate,
      endDate,
      cpCode: this.state.isProductCodeUndefined === undefined ? this.state.realPortfolioTypeArray : [cpCode],
      exchangeCodeObj: this.state.securityType,
    };
    sessionStorage.setItem('JYLS_pageJump', JSON.stringify(JYLS_pageJump));
    this.props.dispatch(routerRedux.push(`/composite/tansactionRecord`));
  };

  exportTrade = () => {
    const par = {
      ...this.state.realParams,
      type: 10,
      isHkStk: 0,
      timestamp: +new Date(),
      cpCode: this.state.isProductCodeUndefined === undefined ? this.state.realPortfolioTypeArray.join(',') : this.state.realParams.cpCode,
    };
    exportFile('api/v1/transactionLs/exprotJnl', par);
  };
  zqCodeChange = (e) => {
    if (e && e.securityType) {
      this.setState({
        securityType: e,
      });
    } else {
      this.setState({
        securityType: undefined,
      });
    }
  };
  render() {
    const { columns, dataSource, currentPage, pageSize, realColumn } = this.state;
    const {
      minDate,
      maxDate,
      workStationM: {
        CombinationType: { portfolioType = undefined },
      },
    } = this.props;
    const formItemLayout = {
      labelCol: {
        span: 2,
      },
      wrapperCol: {
        span: 18,
      },
    };
    let startDate = +moment().subtract(1, 'months').format('YYYYMMDD') - moment(minDate).format('YYYYMMDD') > 0 ? moment().subtract(1, 'months') : moment(minDate);

    return (
      <div className={styles.transactionManage}>
        {/*判断真实/模拟 */}
        {portfolioType === '1' ? (
          <div className={styles.transactionManageSearch}>
            <AdvancedSearch
              // parentId={'transactionManageSearch'}
              onQuery={(e) => {
                this.searchDocker(e);
              }}
              onClear={(e) => {
                this.searchDocker(e);
              }}
              dataSource={[
                {
                  dataIndex: ['startDate', 'endDate'],
                  title: '日期',
                  type: DATA_ENTRY.RANGEDATE,
                  initialValue: [moment(), moment()],
                  onRef: (ref) => {
                    this.state.date = ref;
                  },
                  formItemLayout: {
                    labelCol: {
                      span: this.props.showOnly ? 2 : 4,
                    },
                    wrapperCol: {
                      span: 18,
                    },
                  },
                },
                {
                  dataIndex: 'tradingCode',
                  codeType: codeType.positioned,
                  type: DATA_ENTRY.SECURITIESCODE,
                  onChange: (e) => this.zqCodeChange(e),
                },
              ]}
            />
            <div className={styles.otherBtn}>
              <PrimaryGhostC title={'导出'} onClick={this.exportTrade} style={{ marginRight: 15 }} />
              <PrimaryC title={'更多流水'} onClick={this.moreJournal} />
            </div>
          </div>
        ) : (
          <div className={styles.searchCont}>
            <div className={styles.search} style={{ width: '450px' }}>
              <RangeDateC
                form={this.props.form} // form对象
                title='日期'
                dataIndex={['startDate', 'endDate']}
                onChange={this.dateChange}
                hasDataBD={moment(minDate)}
                hasDataED={moment(maxDate)}
                formItemLayout={formItemLayout}
                onRef={(ref) => (this.RangeDateRef = ref)}
              />
            </div>
            <div>
              <UploadC
                title={<PrimaryC title={'导入交易'} />}
                accept='.xlsx,.xls'
                showUploadList={false}
                type={2}
                isButton={false}
                onUpload={(e) => {
                  this.importTransaction(e);
                }}
                style={{ display: 'inline-block' }}
              />
              <PrimaryGhostC title={'导出交易'} onClick={this.export} style={{ marginRight: '16px', marginLeft: '16px' }} />
              <PrimaryGhostC title={'模板下载'} onClick={this.download} />
            </div>
          </div>
        )}

        <div className={styles.table}>
          <TableC
            columns={portfolioType === '1' ? realColumn : columns}
            dataSource={portfolioType === '1' ? this.state.realDataSource : dataSource}
            rowKey='id'
            loading={portfolioType === '1' ? this.props.loading.effects['tansactionRecordquiryM/queryFnd'] : this.props.loading.effects['workStationM/queryTransactionData']}
            current={currentPage}
            pageSize={pageSize}
            size={'small'}
            onChange={this.handleTableChange}
            scroll={{ x: 1184, y: 220 }}
            total={this.state.total}
          ></TableC>
        </div>
      </div>
    );
  }
}
